
package myPackage;

import java.awt.Color;
import java.io.FileInputStream;
import javax.swing.JTextArea;
//importing JXTA libraries
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.MimeMediaType;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.Message.ElementIterator;
import net.jxta.endpoint.MessageElement;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.InputPipe;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PipeAdvertisement;

// this class will create input pipe for chatting services and shows the incoming messages
public class ChatInput extends Thread implements PipeMsgListener 
{   //Class variables
    private JTextArea txtChat=null , log=null;
    private PeerGroup SaEeDGroup=null;
    private String myPeerID = null;
    private String myPeerName = null;
    private PipeService myPipeService =null;
    private PipeAdvertisement pipeAdv =null;
    private InputPipe pipeInput = null;
    public RBACUtil rbac = new RBACUtil();
    static ChatOutput chatOut;
    public String rolename;
    public boolean rolereceived = false;
     
    /** Creates a new instance of ChatInput */
    public ChatInput(PeerGroup group, JTextArea log, JTextArea chat, ChatOutput cout) 
    {
        this.log = log;
        this.txtChat = chat;
        this.SaEeDGroup = group;
        this.chatOut = cout;
        getServices();
        
    }
    
    public String getRoleName(){
    	if(rolereceived = true)
    	return rolename;
    	else{
    	return null;
    	}
    }
    
    private void getServices()
    {   //Obtaining Peer Group services
        log.append("[+]Getting Services for Chat component...\n");
        myPipeService = SaEeDGroup.getPipeService();
        myPeerID = SaEeDGroup.getPeerID().toString();
        myPeerName = SaEeDGroup.getPeerName();
        
        try{ //Creates input pipe
            FileInputStream is = new FileInputStream("saeedPipe.adv");
            pipeAdv = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(MimeMediaType.XMLUTF8,is);
            is.close();
        }catch(Exception e){
            log.append("[+]Exception: " + e.getMessage()+"\n");
            e.printStackTrace();
            System.exit(-1);
        }
        log.append("[+]Input Pipe Successfully Created.\n");
        
    }
    public void startListening() //This method will start listening for incoming messages thro created pipe
    {
        log.append("[+]Start Listening for Incoming Messages.\n");
        try{
            pipeInput = myPipeService.createInputPipe(pipeAdv,this);
            
        }catch(Exception e){
            log.append("[-]Exception: " + e.getMessage()+"\n");
            return;
        }
        if(pipeInput == null){
            log.append("[-]Failure in Opening Input Pipe :-(\n");
            System.exit(-1);
        }
    }
    public void stopListening() //This method will stop input pipe
    {
        pipeInput.close();
        log.append("[-]Input Pipe Closed for Incomming Message.\n");
    }
    //this listener will respond to incoming messages and show them in Designated area
    public void pipeMsgEvent(PipeMsgEvent ev)
    {
        log.append("[+]Message Received...\n");
        Message myMessage = null;
        try{
            myMessage = ev.getMessage();
            if(myMessage == null){
                return;
            }
        }catch(Exception e){
            System.out.println("[-]Exception happend when trying to get Message element!");
            e.printStackTrace();
        }
        //Assigning values to wanted Tages
        //ElementIterator el = myMessage.getMessageElements();
        String type = myMessage.getMessageElement("Type").toString();
        if (type.equals("Chat")){
        MessageElement me = myMessage.getMessageElement("peerName");
        MessageElement me2 = myMessage.getMessageElement("peerID");
        MessageElement me3 = myMessage.getMessageElement("chatMessage");
        MessageElement me4 = myMessage.getMessageElement("Time");
        
        String peerName = me.toString();
        String peerID = me2.toString();
        String msgContent = me3.toString();
        String sentTime = me4.toString();
        if(me.toString() == null || me2.equals(myPeerID)){
            return;
        }
        else{
         txtChat.append("[ " + me+ "@" + me4 +"]  " + me3 + "\n");
         
        }}
        
        if (type.equals("Location")){
        	String peername = myMessage.getMessageElement("PeerName").toString();
        	String receiver = myMessage.getMessageElement("Receiver").toString();
        	String location = myMessage.getMessageElement("Location").toString();
        	String time = myMessage.getMessageElement("Time").toString();
        	
        	if (receiver.equals(myPeerName))
        	{
        		if(rbac.UpdateLocation(peername,location,time)){
        			System.out.println("Location Info Updated");
        			//get the role_name of peername and send it back
        			wait(5);
        			System.out.println("Wait 5 second for LoT-RBAC system to update the role infomation");
        			String role_name = rbac.getRoleName(peername);
        			System.out.println("Get Role of "+peername+" is "+ role_name);
        			if(role_name != null){        				
        				this.stopListening();
        				chatOut.createRoleInfoMsg(peername, role_name);
        				chatOut.startingPipe();
        				this.startListening();
        				
        			}
        			
        		}
        		else{
        			System.out.println("Location update failed!");
        		}
        	}
        	else{
        		System.out.println("Location info received, but the receiver is not me, just ignore it!");
        	}
        	
        }
       if (type.equals("role_name")){
       	String peername = myMessage.getMessageElement("PeerName").toString();
    	String receiver = myMessage.getMessageElement("Receiver").toString();
    	String roleName = myMessage.getMessageElement("Role_Name").toString();
    	String time = myMessage.getMessageElement("Time").toString();
    	if (receiver.equals(myPeerName))
    	{
    		rolename = roleName;
    		System.out.println("Role Info Received! "+receiver+"has role of "+ roleName +" at "+peername +"'s RBAC");
    		rolereceived = true;
    	}
    	
       }
        
    }
    
    public static void wait (int n){
        long t0,t1;
        t0=System.currentTimeMillis();
        do{
            t1=System.currentTimeMillis();
        }
        while (t1-t0<n*1000);
}

}
